﻿Imports Mystery
Imports MysteryControls

Public Class ReferenceFilter
    Implements IPropertyFilterControl

    Private _content_property As ContentReference

    Private _values As New HashSet(Of IContent)

    Public Property content_property As System.Reflection.PropertyInfo Implements IPropertyFilterControl.content_property
        Get
            Return _content_property.used_in
        End Get
        Set(value As System.Reflection.PropertyInfo)
            _content_property = value.getMysteryAttribute(Of ContentReference)()
        End Set
    End Property

    Public Property label As String Implements IPropertyFilterControl.label

    Public Event haveChanged() Implements IPropertyFilterControl.haveChanged

    Private Sub cbValue_SelectionChanged(sender As System.Object, e As System.Windows.Controls.SelectionChangedEventArgs) Handles cbValue.SelectionChanged
        RaiseEvent haveChanged()
    End Sub

    Public Function Match(content As Mystery.IContent) As Boolean Implements IPropertyFilterControl.Match
        If content Is Nothing Then Return False

        Dim content_value As Object = _content_property.retrive()(content)
        If TypeOf (content_value) Is BaseContentReference Then content_value = DirectCast(content_value, BaseContentReference).getAsEnum()
        Dim contents As IEnumerable(Of IContent) = content_value

        For Each c As IContent In contents
            If Not _values.Contains(c) Then
                addFilterValue(c)
            End If
        Next

        If cbiAll.IsSelected Then Return True

        If contents.Count = 0 Then Return False
        Dim select_value As IContent = _value_map(cbValue.SelectedItem)
        Return contents.Contains(select_value)

    End Function

    Private _value_map As New Dictionary(Of ComboBoxItem, IContent)

    Private Sub addFilterValue(c As IContent)
        If c Is Nothing Then Exit Sub
        _values.Add(c)
        Dim cbi As New ComboBoxItem
        cbValue.Items.Add(cbi)
        Dim refControl As New RefecenceAsText
        cbi.Content = refControl
        'I prefer work with the interface here
        Dim property_control As IPropertyControl = refControl
        'property_control.content = dev_call
        property_control.value = c
        _value_map(cbi) = c
    End Sub

End Class
